//
//  TDPlugin.m
//  Runner
//
//  Created by JiangDong Zhang on 2023/12/9.
//

#import "JDPlugin.h"
#import "YBKeychainUtils.h"

//app名字
#define APP_DISPLAY_NAME        ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"])
//版本号1.0
#define APP_SHORT_VERSION       ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"])
// build号
#define APP_BUNDLE_VERSION      ([[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"])

@interface JDPlugin ()

@property (nonatomic, strong) FlutterMethodChannel *channel;


@end

@implementation JDPlugin


+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
    FlutterMethodChannel *channel = [FlutterMethodChannel methodChannelWithName:@"jd_learn_plugin" binaryMessenger:[registrar messenger]];
    JDPlugin *plugin = [[JDPlugin alloc] initWithChannel:channel];;
    [registrar addMethodCallDelegate:plugin channel:channel];
}

- (instancetype)initWithChannel:(FlutterMethodChannel *)channel {
    self = [super init];
    NSAssert(self, @"super init cannot be nil");
    self.channel = channel;
    return self;
}


//收到flutter调用
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    if ([@"getAppInfo" isEqualToString:call.method]) {
        [self handgetAppInfoMethodWithParam:call.arguments result:result];
    } else if ([call.method isEqualToString:@"jumpAppStore"]) {
        // appStore链接
        NSURL *url = [NSURL URLWithString:@"https://apps.apple.com/cn/app/idxxxxxx"];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    } else {
        if (result) {
            result(FlutterMethodNotImplemented);
        }
    }
}

//获取设备信息
- (void)handgetAppInfoMethodWithParam:(id)arguments result:(FlutterResult)result {
//    NSLog(@"flutter传过来的参数---> %@", arguments);
    /*
     deviceId : 设备唯一id 卸载后也不变
     appName : app名字
     packageName: app id
     appVersion 版本号
     buildNumber 当前版本build号
     device_model 设备机型
     os_version 系统版本
     */
    if (result) {
        result( @{@"deviceId" : [YBKeychainUtils deviceId],
                  @"appName" : APP_DISPLAY_NAME ?: @"",
                  @"packageName" : [[NSBundle mainBundle] bundleIdentifier] ?: @"",
                  @"appVersion" : APP_SHORT_VERSION ?: @"",
                  @"buildNumber" : APP_BUNDLE_VERSION ?: @"",
                  @"device_model" : [UIDevice currentDevice].model ?: @"",
                  @"os_version" : [UIDevice currentDevice].systemVersion ?: @"",
              
                });
    }
   
}

//直接调用flutter测试
- (void)nativeCallFlutterTest {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.channel invokeMethod:@"imagePath" arguments:@{@"key1" : @"ios 调用flutter value"}];
    });
}

@end
